package com.gymmsystem.GYMMSystem.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gymmsystem.GYMMSystem.entity.UserMessage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMessageMapper extends BaseMapper<UserMessage> {

    /**
     * 查询用户的所有消息，已读消息在前，未读消息在后，按创建时间排序
     */
    @Select("SELECT * FROM user_messages WHERE user_id = #{userId} ORDER BY is_read ASC, created_at DESC")
    List<UserMessage> findMessagesByUserId(@Param("userId") Long userId);

    /**
     * 查询用户的未读消息数量
     */
    @Select("SELECT COUNT(*) FROM user_messages WHERE user_id = #{userId} AND is_read = 0")
    int countUnreadMessages(@Param("userId") Long userId);

    /**
     * 将消息标记为已读
     */
    @Update("UPDATE user_messages SET is_read = 1 WHERE id = #{id}")
    int markAsRead(@Param("id") Long id);

    /**
     * 将用户的所有消息标记为已读
     */
    @Update("UPDATE user_messages SET is_read = 1 WHERE user_id = #{userId}")
    int markAllAsRead(@Param("userId") Long userId);

    /**
     * 生成课程预约成功消息
     */
    @Insert("INSERT INTO user_messages (user_id, title, content, type, is_read, related_id, created_at) " +
            "VALUES (#{userId}, '课程预约成功', #{content}, 'COURSE_BOOKING', 0, #{reservationId}, NOW())")
    int insertBookingMessage(@Param("userId") Long userId,
                             @Param("content") String content,
                             @Param("reservationId") Long reservationId);

    /**
     * 生成课程取消预约消息
     */
    @Insert("INSERT INTO user_messages (user_id, title, content, type, is_read, related_id, created_at) " +
            "VALUES (#{userId}, '课程预约取消', #{content}, 'COURSE_CANCEL', 0, #{reservationId}, NOW())")
    int insertCancelMessage(@Param("userId") Long userId,
                            @Param("content") String content,
                            @Param("reservationId") Long reservationId);

    /**
     * 根据预约ID查询相关消息
     */
    @Select("SELECT * FROM user_messages WHERE related_id = #{reservationId} AND type IN ('COURSE_BOOKING', 'COURSE_CANCEL')")
    List<UserMessage> findMessagesByReservationId(@Param("reservationId") Long reservationId);

    /**
     * 删除用户的所有消息
     */
    @Delete("DELETE FROM user_messages WHERE user_id = #{userId}")
    int deleteMessagesByUserId(@Param("userId") Long userId);

    /**
     * 删除已读消息
     */
    @Delete("DELETE FROM user_messages WHERE user_id = #{userId} AND is_read = 1")
    int deleteReadMessages(@Param("userId") Long userId);
}